import {defineStore} from "pinia";
import {LoginFormData} from "@/types/login";
import {useLoginApi} from "@/api/login";
import {useUserStore} from "@/stores/user";

type ILoginVO<T = any> = {
  token: string | null,
  refreshToken: string | null,
}

export const ACCESS_TOKEN = "ACCESS_TOKEN"
export const REFRESH_TOKEN = "REFRESH_TOKEN"

export const useLoginStore = defineStore('login', {
  actions: {
    login(data: LoginFormData): Promise<ILoginVO> {
      return new Promise<ILoginVO>((resolve, reject) => {
        useLoginApi().login(data).then((res) => {
          console.log(res)
          if (res.code === 0 && res.data) {
            useUserStore().setUserInfo(res.data);
            this.setToken(res.data.token)
            this.setRefreshToken(res.data.refresh_token)
            resolve({
              token: res.data.token,
              refreshToken: res.data.refresh_token,
            })
          } else {
            reject(res)
          }
        }).catch(() => {
          reject();
        })
      })
    },
    setToken(token: string) {
      uni.setStorageSync(ACCESS_TOKEN, token)
    },
    getToken() {
      return uni.getStorageSync(ACCESS_TOKEN)
    },
    clearToken() {
      uni.removeStorageSync(ACCESS_TOKEN)
    },
    setRefreshToken(refreshToken: string) {
      uni.setStorageSync(REFRESH_TOKEN, refreshToken)
    },
    getRefreshToken() {
      return uni.getStorageSync(REFRESH_TOKEN)
    },
    clearRefreshToken() {
      uni.removeStorageSync(REFRESH_TOKEN)
    },
    clearAllToken() {
      this.clearToken()
      this.clearRefreshToken()
    },
    logout() {
      return new Promise<boolean>((resolve) => {
        // useLoginApi().logout().then(() => {
        //   this.clearAllToken()
        //   uni.redirectTo({url: '/'})
        // })
        this.clearAllToken()
        uni.redirectTo({url: '/pages/login/index'})
      })
    }
  },
})
